from ..base_downloader import *
from ..base_downloader_firefox import BaseDownloaderFirefox


class Task46(BaseDownloaderFirefox):
    def login(self):
        username_field = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.ID, "username"))
        )
        password_field = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.ID, "password"))
        )
        username_field.send_keys(self.username)
        password_field.send_keys(self.password)

        login_button = WebDriverWait(self.driver, 20).until(
            EC.element_to_be_clickable((By.XPATH, '//input[@type="button" and @value="登陆"]'))
        )
        self.driver.execute_script("arguments[0].click();", login_button)

        original_window = self.driver.current_window_handle

        WebDriverWait(self.driver, 20).until(EC.number_of_windows_to_be(2))

        for window_handle in self.driver.window_handles:
            if window_handle != original_window:
                self.driver.switch_to.window(window_handle)
                break

        self.driver.switch_to.window(original_window)
        self.driver.close()

        self.driver.switch_to.window(window_handle)

        self.random_sleep(0.5)
        self.accept_alert_dialog()
        self.random_sleep(1.5)

    def retrieve_data(self):
        self.click_query_button()       
        self.set_start_and_end_dates()
        self.click_retrieve_button()

    def click_query_button(self):
        try:
            query_button = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, '//span[text()="商品流向查询"]'))
            )
            query_button.click()

        except Exception as e:
            logger.exception(f"An error occurred while clicking the query button: {e}")

    def set_start_and_end_dates(self):

        WebDriverWait(self.driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.ID,'iframe0')))
        
        start_year, start_month, start_day = re.findall('\d+', self.start_date)
        end_year, end_month, end_day = re.findall('\d+', self.end_date)

        start_year_box = Select(WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located((By.ID, 'WucDateTime1_DropDownList1'))))
        start_year_box.select_by_value(start_year)

        start_month_box = Select(WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located((By.ID, 'WucDateTime1_DropDownList2'))))
        start_month_box.select_by_value(str(int(start_month)))

        start_day_box = Select(self.driver.find_element(By.ID, 'WucDateTime1_DropDownList3'))
        start_day_box.select_by_value(str(int(start_day)))

        end_year_box = Select(WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located((By.ID, 'WucDateTime2_DropDownList1'))))
        end_year_box.select_by_value(end_year)

        end_month_box = Select(self.driver.find_element(By.ID, 'WucDateTime2_DropDownList2'))
        end_month_box.select_by_value(str(int(end_month)))

        end_day_box = Select(self.driver.find_element(By.ID, 'WucDateTime2_DropDownList3'))
        end_day_box.select_by_value(str(int(end_day)))

        self.capture_screenshot()

    def click_retrieve_button(self):
        try:
            retrieve_button = self.driver.find_element(By.ID, 'Button2')
            retrieve_button.click()
        except Exception as e:
            logger.exception(f"An error occurred while clicking the retrieve button: {e}")

    def export_excel(self):
        self.capture_screenshot()
        export_button = self.driver.find_element(By.ID, "ButtonExport")
        export_button.click()

        downloaded_file = self.get_latest_downloaded_file()

        new_file_name = f"{self.site_name}_exported_click_button.xlsx"
        destination_path = os.path.join(self.task_download_dir, new_file_name)

        data_frame = pd.read_html(downloaded_file)[0]
        data_frame.to_excel(destination_path, index=False)

        logger.info(f"Processed and saved file to: {destination_path}")

        self.random_sleep(8)
        self.delete_downloaded_files()

    def page_html_to_excel(self):
        self.driver.switch_to.default_content()
        data_frame = pd.read_html(self.driver.page_source)[0]
        target_path = os.path.join(
            self.task_download_dir, f"{self.site_name}_page_html_to_excel.xlsx"
        )
        data_frame.to_excel(target_path, index=False)


    def download_file(self):
        #self.page_html_to_excel()  # One way to download the Excel file
        self.export_excel()        # Another way to download the Excel file; use either method

    def delete_downloaded_files(self):
        """Delete the original downloaded file after processing."""
        try:
            downloaded_file = self.get_latest_downloaded_file()
            if os.path.exists(downloaded_file):
                os.remove(downloaded_file)
                logger.info(f"Deleted original downloaded file: {downloaded_file}")
        except Exception as e:
            logger.error(f"Error deleting downloaded file: {e}")